package com.wuwei.aliocr.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wuwei.aliocr.domain.LessonRecord;
import com.wuwei.aliocr.mapper.LessonRecordMapper;
import com.wuwei.aliocr.service.PaiKeService;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

import static com.wuwei.aliocr.utils.HttpUtils.doGet;

@Service
public class PaiKeServiceImpl implements PaiKeService {

//    @Resource
//    ShangKeRiQiMapper shangKeRiQiMapper;

    @Resource
    private LessonRecordMapper lessonRecordMapper;

    //添加工作日到数据库中
    @Override
    public void addWorkDay() {
//        // 获取当前日期
//        Calendar calendar = Calendar.getInstance();
//
//        //获取法定节假日列表
//        ArrayList<String> arrayList = getJieJiaRi();
//
//        for (int i = 61; i < 120; i++) {
//
//            // 获取明天的日期
//            calendar.add(Calendar.DAY_OF_YEAR, 1);
//
//            // 获取星期几，1 表示星期日，2 表示星期一，以此类推
//            int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
//
//            // 将星期几转换为中文描述
//            String weekDay = getWeekDayInChinese(dayOfWeek);
//            weekDay="星期"+weekDay;
//            int Year = calendar.get(Calendar.YEAR);
//            int Month = calendar.get(Calendar.MONTH) + 1;
//            int Day = calendar.get(Calendar.DAY_OF_MONTH);
//            String date = Year + "-" + Month + "-" + Day;
//            date.trim();
//            //如果当天在法定节假日列表里就不存储到数据库
//            if (!arrayList.contains(date)) {//法定节假日不上课
//                //除了法定节假日以外周日也不上课
//                if (!weekDay.equals("日")){
//                    System.out.println(date+","+weekDay);
//                    //将需要上课的日期存到数据库中
//                    ShangKeRiQi shangKeRiQi = new ShangKeRiQi();
//                    shangKeRiQi.setDate(date);
//                    shangKeRiQi.setWeekend(weekDay);
//                    shangKeRiQiMapper.insert(shangKeRiQi);
//                }
//            }
//        }
    }

    //获取周六日的安排


    //获取法定节假日
    @Override
    public ArrayList<String> getJieJiaRi() {
        String host = "http://v.juhe.cn";
        String path = "/calendar/month";
        String method = "GET";

        String riqi = "2023-11";

        // 构建查询参数
        Map<String, String> querys = new HashMap<>();
        //聚合API网址https://dashboard.juhe.cn/data/index/my
        querys.put("key", "7e0e00c0ba6cb198b4bac7e83b14f54a");//聚合api的token
        //riqi的格式为2019-9
        querys.put("year-month", riqi);

        // 构建请求头部信息
        Map<String, String> headers = new HashMap<>();

        try {
            HttpResponse response = doGet(host, path, method, headers, querys);
            HttpEntity entity = response.getEntity();
            //如果发出http请求可以使用这行代码
//            if (entity != null) {
            if (entity != null) {
                // 将实体内容转换为字符串
                String responseBody = EntityUtils.toString(entity);

                //这里为了测试使用已获得的数据
//                String res = "{\"reason\":\"Success\",\"result\":{\"data\":{\"year\":\"2023\",\"year-month\":\"2023-9\",\"holiday\":\"[{\\\"desc\\\":\\\"9月29日放假调休，共1天\\\",\\\"festival\\\":\\\"2023-9-29\\\",\\\"list\\\":[{\\\"date\\\":\\\"2023-9-29\\\",\\\"status\\\":\\\"1\\\"}],\\\"list#num#\\\":1,\\\"name\\\":\\\"中秋节\\\",\\\"rest\\\":\\\"\\\"},{\\\"desc\\\":\\\"9月30日至10月6日放假调休，共7天。10月7日（星期六）、10月8日（星期日）上班\\\",\\\"festival\\\":\\\"2023-10-1\\\",\\\"list\\\":[{\\\"date\\\":\\\"2023-9-30\\\",\\\"status\\\":\\\"1\\\"},{\\\"date\\\":\\\"2023-10-1\\\",\\\"status\\\":\\\"1\\\"},{\\\"date\\\":\\\"2023-10-2\\\",\\\"status\\\":\\\"1\\\"},{\\\"date\\\":\\\"2023-10-3\\\",\\\"status\\\":\\\"1\\\"},{\\\"date\\\":\\\"2023-10-4\\\",\\\"status\\\":\\\"1\\\"},{\\\"date\\\":\\\"2023-10-5\\\",\\\"status\\\":\\\"1\\\"},{\\\"date\\\":\\\"2023-10-6\\\",\\\"status\\\":\\\"1\\\"},{\\\"date\\\":\\\"2023-10-7\\\",\\\"status\\\":\\\"2\\\"},{\\\"date\\\":\\\"2023-10-8\\\",\\\"status\\\":\\\"2\\\"}],\\\"list#num#\\\":9,\\\"name\\\":\\\"国庆节\\\",\\\"rest\\\":\\\"\\\"}]\",\"holiday_array\":[{\"desc\":\"9月29日放假调休，共1天\",\"festival\":\"2023-9-29\",\"list\":[{\"date\":\"2023-9-29\",\"status\":\"1\"}],\"list#num#\":1,\"name\":\"中秋节\",\"rest\":\"\",\"list_num\":1},{\"desc\":\"9月30日至10月6日放假调休，共7天。10月7日（星期六）、10月8日（星期日）上班\",\"festival\":\"2023-10-1\",\"list\":[{\"date\":\"2023-9-30\",\"status\":\"1\"},{\"date\":\"2023-10-1\",\"status\":\"1\"},{\"date\":\"2023-10-2\",\"status\":\"1\"},{\"date\":\"2023-10-3\",\"status\":\"1\"},{\"date\":\"2023-10-4\",\"status\":\"1\"},{\"date\":\"2023-10-5\",\"status\":\"1\"},{\"date\":\"2023-10-6\",\"status\":\"1\"},{\"date\":\"2023-10-7\",\"status\":\"2\"},{\"date\":\"2023-10-8\",\"status\":\"2\"}],\"list#num#\":9,\"name\":\"国庆节\",\"rest\":\"\",\"list_num\":9}]}},\"error_code\":0}";

                // 将JSON字符串解析为JSONObject
                JSONObject jsonObject = JSON.parseObject(responseBody);

                JSONArray holiday_array = jsonObject.getJSONObject("result")
                        .getJSONObject("data")
                        .getJSONArray("holiday_array");
                ArrayList<String> jieJiaRiList = new ArrayList<>();

                // 遍历JSONArray，获取每个节假日的名称和开始日期
                for (int i = 0; i < holiday_array.size(); i++) {
                    JSONObject holidayObject = holiday_array.getJSONObject(i);
                    String list = holidayObject.getString("list");
                    JSONArray holidayList = JSON.parseArray(list);
                    for (int j = 0; j < holidayList.size(); j++) {
                        JSONObject obj = holidayList.getJSONObject(j);
                        String date = obj.getString("date");
                        String status = obj.getString("status");
                        //status等于1的就代表是节假日
                        if (status.equals("1")){
                            //将节假日存到数组中
                            jieJiaRiList.add(date.trim());
                        }
                    }
                }
                return jieJiaRiList;
            }
            // 处理响应结果...
        } catch (Exception e) {
            // 异常处理...
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据传入的日期从数据库中查询当天有谁在上课
     * @param formattedDate
     */
    @Override
    public List<LessonRecord> getPaikeForTheDate(String formattedDate) {
        LambdaQueryWrapper<LessonRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(formattedDate!=null, LessonRecord::getDate,formattedDate);
        List<LessonRecord> lessonRecords = lessonRecordMapper.selectList(queryWrapper);
        return lessonRecords;
    }


    private static String getWeekDayInChinese(int dayOfWeek) {
        switch (dayOfWeek) {
            case Calendar.SUNDAY:
                return "日";
            case Calendar.MONDAY:
                return "一";
            case Calendar.TUESDAY:
                return "二";
            case Calendar.WEDNESDAY:
                return "三";
            case Calendar.THURSDAY:
                return "四";
            case Calendar.FRIDAY:
                return "五";
            case Calendar.SATURDAY:
                return "六";
            default:
                return "";
        }
    }
}
